<?php
	
	function addcourse($data){
			$prefix = "timetable_";
			global $wpdb;
		

			$type = $data['table_name'];
			
			if($type == 'client'){

				$client_id = $data['client'];
				$course_id = $data['course'];
				$course_summ = $data['summ'];
				$date = $data['date'];

				$course_query = "SELECT idcourse course_id,  course_name, course_basecost, course_totalcount FROM {$prefix}course WHERE idcourse = $course_id";
				$course = $wpdb->get_row($course_query, ARRAY_A);	
				if($course_summ == '' || $summ_summ == 0 ){
					$course_summ = $course['course_basecost'];
				}
				$course_totalcount = $course['course_totalcount'] ;


				$teacher_query = "SELECT teacher_id FROM {$prefix}teachercourse WHERE course_id = $course_id";
				$teacher = $wpdb->get_row($teacher_query, ARRAY_A);	
				$teacher_id = $teacher['teacher_id'];




				$query = "INSERT INTO 
					{$prefix}clientcourse 
					( 
						course_id,
						paystatus_id,
						teacher_id, 
						clientcourse_lessontotal,
						clientcourse_count, 
						client_id,
						clientcourse_begin
					) 
				VALUES( 
					$course_id , 
					1 , 
					$teacher_id , 
					$course_totalcount ,
					0 , 
					$client_id ,STR_TO_DATE('{$date}', '%d-%m-%Y'))";
				
				$query_if_exist = "SELECT count(*) count FROM {$prefix}clientcourse WHERE client_id = $cllient_id AND course_id = $course_id";

				$res_if_exist = $wpdb->get_row($query_if_exist, ARRAY_A);

				if($res_if_exist["count"] == 0) {				

					$wpdb->query($query);

				}


			}elseif ($type == 'teacher') {
				echo "teacher";
				echo json_encode($data);
				$teacher_id = $data['teacher_id'];
				$course_id = $data['course_id'];
				$query_if_exist = "SELECT count(*) count FROM {$prefix}clientcourse WHERE teacher_id = $teacher_id AND course_id = $course_id";
				$res_if_exist = $wpdb->get_row($query_if_exist, ARRAY_A);

				echo json_encode($res_if_exist);

				if($res_if_exist["count"] == 0) {	

					$wpdb->insert(
							"{$prefix}teachercourse",
							array(
									"teacher_id"=> $teacher_id,
									"course_id" => $course_id
								),
							array(
									'%d',
									'%d'
								)
					);	
				}
			}	
			
	}

	function delcourse($data){
			$prefix = "timetable_";
			global $wpdb;
			$type = $data['table_name'];
			if ($type == 'teacher') {
				echo "teacher";
				echo json_encode($data);
				$teacher_id = $data['teacher_id'];
				$course_id = $data['course_id'];

				$q = "DELETE FROM {$prefix}teachercourse WHERE teacher_id = $teacher_id AND course_id = $course_id";
				$wpdb->query($q);
									
			}	
			
	}


?>